package com.bxmdm.ragdemo.service;

import com.bxmdm.ragdemo.dto.DeepseekRequest;
import com.bxmdm.ragdemo.dto.DeepseekResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;
import java.util.List;

/**
 * DeepSeek API 服务类
 */
@Service
public class DeepseekService {

    private final WebClient webClient;

    public DeepseekService(
            @Value("${deepseek.api.url}") String apiUrl,
            @Value("${deepseek.api.key}") String apiKey) {

        // 配置HTTP客户端，增加超时设置
        HttpClient httpClient = HttpClient.create()
                .responseTimeout(Duration.ofSeconds(120));

        this.webClient = WebClient.builder()
                .baseUrl(apiUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024))
                .build();
    }

    /**
     * 调用 DeepSeek API 进行对话
     * 
     * @param userQuestion 用户问题
     * @return DeepSeek 响应
     */
    public Mono<DeepseekResponse> callDeepseekApi(String userQuestion) {
        // 构建请求，使用传入的问题变量
        DeepseekRequest request = DeepseekRequest.builder()
                .model("DeepSeek-R1")
                .messages(List.of(
                        new DeepseekRequest.Message("user", userQuestion)  // 使用参数变量
                ))
                .temperature(0.7)
                .maxTokens(1024)
                .build();

        return webClient.post()
                .uri("/chat/completions")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .bodyValue(request)
                .retrieve()
                .bodyToMono(DeepseekResponse.class);
    }

    /**
     * 同步调用 DeepSeek API
     * 
     * @param userQuestion 用户问题
     * @return 响应内容
     */
    public String callDeepseekSync(String userQuestion) {
        try {
            DeepseekResponse response = callDeepseekApi(userQuestion).block();
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                System.out.println("DeepSeek 响应: " + response);
                
                return response.getChoices().get(0).getMessage().getContent();
            }
            return "DeepSeek API 未返回有效响应";
        } catch (Exception e) {
            return "调用 DeepSeek API 出错: " + e.getMessage();
        }
    }
}
